<html>
    <head>
        <title>IoT City Test Portal</title>
        <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="https://code.highcharts.com/stock/highstock.js"></script>
        <script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  
        <script src="{{ url_for("static", filename="ws.js") }}"></script>
        
        <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
        <link href='{{ url_for("static", filename="style.css") }}' rel='stylesheet' type='text/css'>
    </head>
    <body>
        <script type="text/javascript">
            var service_url="http://localhost:8000/authenticated";
            var token=localStorage.getItem('access_token');

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status != 200) {
                        window.location.replace("/login");
                        return false;
                    }
                    return true;
                }
            }
            xhr.open("GET", service_url, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            xhr.send();
        </script>

        <div class="sidenav">
            <a href="/">Home</a>
            <a href="/verticals">Verticals</a>
            <a href="/devices">Devices</a>
            <a href="/subscriptions">Subscriptions</a>
            <a href="/alerts">Alerts</a>
            <a href="/triggered">Triggered</a>
        </div>

        <div body style="margin-left: 200px;">
            <h3>Device ID: {{device_id}}</h3>
            <table id="streams">
                <tr>
                    <td>Name</td>
                    <td>Description</td>
                    <td>Device ID</td>
                    <td>Actuator</td>
                    <td>Send value</td>
                    <td>Delete</td>
                </tr>
            </table>

            <button id="create-stream">Create new stream</button>
        </div>
        
        <div id="dialog-form" title="Add Stream">
         
          <form>
            <fieldset>
              <label for="name">Name</label>
              <input type="text" name="name" id="name" value="" class="text ui-widget-content ui-corner-all">
              <label for="description">Description</label>
              <input type="text" name="description" id="description" value="" class="text ui-widget-content ui-corner-all">
              <label for="actuator">Actuator (true/false)</label>
              <input type="text" name="actuator" id="actuator" value="" class="text ui-widget-content ui-corner-all">
         
              <!-- Allow form submission with keyboard without duplicating the dialog button -->
              <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
            </fieldset>
          </form>
        
        <script type="text/javascript">
            var service_url="http://localhost:8000";
            $( function() {
                var dialog, form,
            
                name = $( "#name" ),
                description = $ ( "#description" );
                actuator = $ ( "#actuator" );
            
            
                function addStream() {
                    var xhr = new XMLHttpRequest();
                    data = {"name": document.getElementById("name").value, "description": document.getElementById("description").value,
                            "actuator": document.getElementById("actuator").value};
                    xhr.open("POST", service_url+"/device/{{ device_id }}/stream", true);
                    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                    xhr.setRequestHeader('ACCOUNT-ID', 'ua1');
                    xhr.setRequestHeader('ACCOUNT-SECRET', '8ik8fm0h8mqer821agae3qg29ve1kl84d9b0svsiesqj52lil59g');
                    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'));
                    xhr.send(JSON.stringify(data));
                    xhr.onloadend = function () {
                        window.location.reload();
                    };
                }
            
                dialog = $( "#dialog-form" ).dialog({
                    autoOpen: false,
                    height: 400,
                    width: 350,
                    modal: true,
                    buttons: {
                        "Add Stream": addStream,
                        Cancel: function() {
                            dialog.dialog( "close" );
                        }
                    },
                    close: function() {
                    form[ 0 ].reset();
                    }
                });
             
                form = dialog.find( "form" ).on( "submit", function( event ) {
                    event.preventDefault();
                    addStream();
                });
             
                $( "#create-stream" ).button().on( "click", function() {
                    dialog.dialog( "open" );
                });
            });

            var url = service_url+"/device/{{ device_id }}/stream";
            $.ajax({ url: url,
                headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')},
                success: function(data) {
                    values = data["values"];

                    for(value in values){
                        var table = document.getElementById("streams");
                        var row = table.insertRow(-1);
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        var cell3 = row.insertCell(2);
                        var cell4 = row.insertCell(3);
                        var cell5 = row.insertCell(4);
                        var cell6 = row.insertCell(5);
                        
                        var button = document.createElement("button");
                        (function(name){
                            button.addEventListener('click', function(){ deleteStream(name); }, true);
                        })(values[value]["name"]);
                        button.innerHTML = "Delete";

                        var button2 = document.createElement("button");
                        (function(name){
                            button2.addEventListener('click', function(){ 
                                sendValue(name);
                            }, true);
                        })(values[value]["name"]);
                        button2.innerHTML = "Send...";
                        
                        cell1.innerHTML = values[value]["name"];
                        cell2.innerHTML = values[value]["description"];
                        cell3.innerHTML = values[value]["device_id"];
                        cell4.innerHTML = values[value]["actuator"];
                        if(values[value]["actuator"]){
                            cell5.appendChild(button2);
                        }
                        cell6.appendChild(button);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                }
            });

            function sendValue(stream_name){
                value = prompt("Enter the value");
                var xhr = new XMLHttpRequest();
                xhr.open("POST", service_url+"/device/{{ device_id }}/stream/"+stream_name, true);
                data = {"value": value};
                xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                xhr.setRequestHeader('ACCOUNT-ID', 'ua1');
                xhr.setRequestHeader('ACCOUNT-SECRET', '8ik8fm0h8mqer821agae3qg29ve1kl84d9b0svsiesqj52lil59g');
                xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'));
                xhr.send(JSON.stringify(data));
                xhr.onloadend = function () {
                    location.reload();
                };
            }

            function deleteStream(name){
                var xhr = new XMLHttpRequest();
                xhr.open("DELETE", service_url+"/device/{{ device_id }}/stream/"+name, true);
                xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                xhr.setRequestHeader('ACCOUNT-ID', 'ua1');
                xhr.setRequestHeader('ACCOUNT-SECRET', '8ik8fm0h8mqer821agae3qg29ve1kl84d9b0svsiesqj52lil59g');
                xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'));
                xhr.send();
                xhr.onloadend = function () {
                    location.reload();
                };
            }

        </script>
    </body>
</html>

